package com.wz.activity;

import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.baidu.tts.auth.AuthInfo;
import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.wz.adapter.ViewPagerAdapter;
import com.wz.util.AndroidFileUtil;
import com.wz.util.ToastUtil;

public class MainActivity extends AppCompatActivity {

	// 语音合成客户端
	private SpeechSynthesizer mSpeechSynthesizer;
	private String mSampleDirPath;
	private static final String SAMPLE_DIR_NAME = "baiduTTS";
	private static final String SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat";
	private static final String SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat";
	private static final String TEXT_MODEL_NAME = "bd_etts_text.dat";
	// private static final String LICENSE_FILE_NAME =
	// "temp_license_2016-10-05";
	private static final String ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat";
	private static final String ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat";
	private static final String ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat";

	private TabLayout mtaLayout;
	private ViewPager mviewPager;
	private String[] titles = new String[] { "联系人", "节日短信", "发送记录" };

	private static MainActivity ma;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ma = this;

		initViews();
		
		initialEnv();
		startTTS();
		
	}

	// 获取当前对象实例
	public static MainActivity instance() {
		return ma;
	}

	private void initViews() {
		/* mtaLayout 的父亲控件为 LinearLayout时滑动才有效果 */
		mtaLayout = (TabLayout) findViewById(R.id.wz_tablayout);
		mviewPager = (ViewPager) findViewById(R.id.wz_viewpager);

		mviewPager.setAdapter(new ViewPagerAdapter(this.getSupportFragmentManager(), titles));

		mtaLayout.setupWithViewPager(mviewPager);
	}
	
	 /**
	  * 初始化语音合成环境
	  */
	private void initialEnv() {
		if (mSampleDirPath == null) {
			String sdcardPath = Environment.getExternalStorageDirectory().toString();
			mSampleDirPath = sdcardPath + "/" + SAMPLE_DIR_NAME;
		}

		AndroidFileUtil.makeDir(mSampleDirPath);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" + SPEECH_MALE_MODEL_NAME);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, TEXT_MODEL_NAME, mSampleDirPath + "/" + TEXT_MODEL_NAME);
		//AndroidFileUtil.copyFromAssetsToSdcard(this, false, LICENSE_FILE_NAME, mSampleDirPath + "/" + LICENSE_FILE_NAME);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, "english/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME, mSampleDirPath + "/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, "english/" + ENGLISH_SPEECH_MALE_MODEL_NAME, mSampleDirPath + "/" + ENGLISH_SPEECH_MALE_MODEL_NAME);
		AndroidFileUtil.copyFromAssetsToSdcard(this, false, "english/" + ENGLISH_TEXT_MODEL_NAME, mSampleDirPath + "/" + ENGLISH_TEXT_MODEL_NAME);

	}

	// 初始化语音合成客户端并启动
	private void startTTS() {
		// 获取语音合成对象实例
		this.mSpeechSynthesizer = SpeechSynthesizer.getInstance();
		// 设置context
		this.mSpeechSynthesizer.setContext(this.getApplicationContext());
		// 设置语音合成状态监听器
		this.mSpeechSynthesizer.setSpeechSynthesizerListener(new MySpeechSynthesizerListener());
		// 设置在线语音合成授权，需要填入从百度语音官网申请的api_key和secret_key
		this.mSpeechSynthesizer.setApiKey(Constant.API_KEY, Constant.SECRET_KEY);
		// 设置离线语音合成授权，需要填入从百度语音官网申请的app_id
		this.mSpeechSynthesizer.setAppId(Constant.APP_ID);

		// 本地授权文件路径,如未设置将使用默认路径.设置临时授权文件路径，
		// LICENCE_FILE_NAME请替换成临时授权文件的实际路径，仅在使用临时license文件时需要进行设置
		// 如果在[应用管理]中开通了正式离线授权，不需要设置该参数，建议将该行代码删除（离线引擎）
		// 如果合成结果出现临时授权文件将要到期的提示，说明使用了临时授权文件，请删除临时授权即可。
		// this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_LICENCE_FILE, mSampleDirPath + "/" + LICENSE_FILE_NAME);
		
		// 文本模型文件路径 (离线引擎使用)
		this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mSampleDirPath + "/" + TEXT_MODEL_NAME);
		// 声学模型文件路径 (离线引擎使用)
		this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mSampleDirPath + "/" + SPEECH_FEMALE_MODEL_NAME);
		// 中级音量，范围[0-9]
		this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_VOLUME, "8");
		// 中速, 范围[0-9]
		this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEED, "4");
		// 发音人（在线引擎），可用参数为0,1,2,3。。。（服务器端会动态增加，各值含义参考文档，
		// 以文档说明为准。0--普通女声，1--普通男声，2--特别男声，3--情感男声。。。）
		// this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER,
		// "0");
		// 设置Mix模式的合成策略
		// this.mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE,
		// SpeechSynthesizer.MIX_MODE_DEFAULT);

		// 获取语音合成授权信息
		AuthInfo authInfo = mSpeechSynthesizer.auth(TtsMode.MIX);
		// 判断授权信息是否正确，如果正确则初始化语音合成器并开始语音合成，如果失败则做错误处理
		if (authInfo.isSuccess()) {
			mSpeechSynthesizer.initTts(TtsMode.MIX);
			MainActivity.instance().speak("欢迎使用智能拨号APP");
		} else {
			// 授权失败
			Log.d("Tag", "语音合成授权失败");
		}
	}

	/**
	 * 需要合成的文本text的长度不能超过1024个GBK字节。
	 */
	public void speak(String text) {
		int result = this.mSpeechSynthesizer.speak(text);
		if (result < 0) {
			ToastUtil.showShort(this.getApplicationContext(), "语音合成失败");
		}
	}

	@Override
	protected void onDestroy() {
		this.mSpeechSynthesizer.release();
		super.onDestroy();
	}

	/**
	 * 内部类,语音合成监听器
	 */
	class MySpeechSynthesizerListener implements SpeechSynthesizerListener {

		public void onError(String arg0, SpeechError arg1) {
			// 监听到出错，在此添加相关操作
		}

		public void onSpeechFinish(String arg0) {
			// 监听到播放结束，在此添加相关操作
		}

		public void onSpeechProgressChanged(String arg0, int arg1) {
			// 监听到播放进度有变化，在此添加相关操作
		}

		public void onSpeechStart(String arg0) {
			// 监听到合成并播放开始，在此添加相关操作
		}

		public void onSynthesizeDataArrived(String arg0, byte[] arg1, int arg2) {
			// 监听到有合成数据到达，在此添加相关操作
		}

		public void onSynthesizeFinish(String arg0) {
			// 监听到合成结束，在此添加相关操作
		}

		public void onSynthesizeStart(String arg0) {
			// 监听到合成开始，在此添加相关操作
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
